<!DOCTYPE html>
<html>
<head>
	<title>Grackle Diagram, jQuery, svgweb editor</title>
	<link rel="stylesheet" rev="stylesheet" href="css/examples.css" type="text/css" media="screen" />
    <script src="svgweb/src/svg.js" data-path="svgweb/src"></script>
	<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
	<script type="text/javascript" src="js/jquery.nth-graph.js"></script>
	<script type="text/javascript" src="js/jquery.nth-graph-edit.js"></script>
	<script type="text/javascript" src="js/json2.js"></script>
	<script type="text/javascript" src="js/jsonschema-b4.js"></script>
	<script type="text/javascript">
	// <![CDATA[	
    var gv1;
    
	$(document).ready(function() {
		$("#graph-node-properties").hide();
		var firstGraph = {"graph":{"id":1, "version":"0.03", "traversal":{"start":0}}
				, "nodes":[
							  {"name":"start"}
							, {"ele":"#a1", "type":"in", "input":{"event":{"keyup":"traverse"}}}
							, {"ele":"#b1", "type":"in", "input":{"event":{"keyup":"traverse"}}}
							, {"ele":"#sum", "type":"out", "output":{"event":{"change":"immediately"}, "type":"text"}}
							, {"name":"calc"
								, "process":"function() {"+
														"  this.sum = this.a1 + this.b1;"+
														"}"
							}
							, {"name":"stop"}
				  ]
				, "edges":[
							  {"from":0, "to":4, "type":"trans"}
							, {"from":4, "to":1, "type":"get", "name":"a1"}
							, {"from":4, "to":2, "type":"get", "name":"b1"}
							, {"from":4, "to":5, "type":"trans"}
							, {"from":4, "to":3, "type":"set", "name":"sum"}
				  ]
			};
		//$("#example1").nthGraph({ "cg":firstGraph });  
		var firstGraphView = {"graph":{"name":"1", "version":"0.03"}  
				, "nodes":[
							  {"cx":60, "cy":40}
							, {"cx":110, "cy":100}
							, {"cx":200, "cy":120}
							, {"cx":290, "cy":100}
							, {"cx":200, "cy":40, "r":35}
							, {"cx":360, "cy":40}
				  ]
				, "edges":[
							  {"tail":{"angle":350}, "head":{"angle":190}}
							, {"tail":{"angle":120}, "head":{"angle":290}}
							, {"tail":{"angle":90}, "head":{"angle":270}}
							, {"tail":{"angle":350}, "head":{"angle":190}}
							, {"tail":{"angle":60}, "head":{"angle":250}}
				  ]
			};
		gv1 = $("#diagram-group").nthGraphView({ "g":firstGraph, "gv":firstGraphView});
		$("#diagram-1-gv-text").val(JSON.stringify(firstGraphView, null, '  '));
		$("#diagram-1-gv-text").bind("blur", function() {
		    var json_text = $("#diagram-1-gv-text").val();
            var gr = JSON.parse(json_text);
            gv1.setGraphView(gr);
        });
		$("#diagram-1-gr-text").val(JSON.stringify(firstGraph, null, '  '));
		$("#diagram-1-gr-text").bind("blur", function() {
		    var json_text = $("#diagram-1-gr-text").val();
            var gr = JSON.parse(json_text);
            gv1.setGraph(gr);
            //$("#example1").nthGraph({ "cg":gr });
        });
        $("body").bind("updated-graph", function () {
            var gv = gv1.getGraphView();
        	var g = gv1.getGraph();

            $("#diagram-1-gv-text").val(JSON.stringify(gv, null, ' '));

            $("#diagram-1-gr-text").val(JSON.stringify(g, null, ' '));
        });

        $("body").bind("export-node-properties", function(event, i, node) {
            $("#graph-node-properties").show();
            $("#graph-edge-properties").hide();
            
            $("#graph-node-index").val(i)
            $("#graph-node-properties-text").val(JSON.stringify(node||"{}", "  "));
        });

        $("body").bind("export-edge-properties", function(event, i, edge) {
            $("#graph-edge-properties").show();
            $("#graph-node-properties").hide();
            $("#graph-edge-index").val(i)
            $("#graph-edge-properties-text").val(JSON.stringify(edge||"{}", "  "));
        });

        $("#hide-show-diagram-1-json").bind("click", function(){
            $("#diagram-1-json-text").toggle();
        });
        $("#redraw-diagram-1").bind("click", function(){
            gv1.reDraw();
        });

        $("#submit-graph-node-properties").bind("click", function(){
            var i = $("#graph-node-index").val();
            var node = JSON.parse($("#graph-node-properties-text").val());
            var node_schema = JSON.parse($("#graph-node-schema").text());
            var check = JSONSchema.validate(node, node_schema);
            if (check && check.valid === true) {
                $("body").trigger("write-graph-node-properties", [i, node]);
            }
            else {
                alert(JSON.stringify(check.errors, '  '));
            }
        });
        $("#submit-graph-edge-properties").bind("click", function(){
            var i = $("#graph-edge-index").val();
            var edge = JSON.parse($("#graph-edge-properties-text").val());
            var edge_schema = JSON.parse($("#graph-edge-schema").text());
            var check = JSONSchema.validate(edge, edge_schema);
            if (check && check.valid === true) {
                $("body").trigger("write-graph-edge-properties", [i, edge]);
            }
            else {
                alert(JSON.stringify(check.errors, '  '));
            }
        });

	});
	function list_graphs() {
        
    	var list_service_url = "services/list_graphs.php";
    	$("#editor_open_button").attr("disabled","disabled");
        $.ajax({
        	type: 'GET',
        	data: {},
        	processData: true,
        	url: list_service_url,
        	dataType: "json",
        	"error": function(XMLHttpRequest, textStatus, errorThrown){
        		alert(textStatus + " | " + errorThrown);
        	},
        	"success": function(data){
                if (data) {
                    $.each(data, function(i, li){
                        $("#list_graphs_dialog").append('<div><a href+"#" onclick="load_graph('+li.graph_id+');return false;">'+li.name+'</a></div>');
                    });
                    $("#list_graphs_dialog").show();
                }
            }
        });
    }

    function load_graph(graph_id) {
    	var load_service_url = "services/load_graph.php";
        $.ajax({
        	type: 'POST',
        	data: {"graph_id":graph_id, "view_id":"0"},
        	processData: true,
        	url: load_service_url,
        	dataType: "json",
        	"error": function(XMLHttpRequest, textStatus, errorThrown) {
        		alert(textStatus + " ||| " + errorThrown);
        		$("#editor_open_button").removeAttr("disabled");
        	},
        	"success": function(data) { 
                var gv = JSON.parse(data.default_view);
                var g = JSON.parse(data.graph);
                gv1.setGraphView(gv);
                gv1.setGraph(g);
                gv1.assignId(graph_id)
                gv1.reDraw();
                $("#list_graphs_dialog").empty().hide();
        	    $("#editor_open_button").removeAttr("disabled");
            }
        });
    }

	function save_graph() {
        var gv = gv1.getGraphView();
    	var g = gv1.getGraph();
        var i = g.graph.id;
    	var save_service_url = "services/save_graph.php";
    	$("#editor_save_button").attr("disabled","disabled");
        if(i<1) {alert("graph id id not valid."); return;}
        g = JSON.stringify(g);
        gv = JSON.stringify(gv);
        $.ajax({
        	type: 'POST',
        	data: {"graph_id":i, "g":g, "gv":gv},
        	processData: true,
        	url: save_service_url,
        	"error": function(XMLHttpRequest, textStatus, errorThrown){
        		alert(textStatus + " | " + errorThrown);
            	$("#editor_save_button").removeAttr("disabled");
        	},
        	"success": function(data){
            	$("#editor_save_button").removeAttr("disabled");
            },
        	dataType: "json"
        });
    }
	
	// ]]>
	</script>
</head>
<body>
<h1>An "nth-graph" Editor</h1>
<p>Test of an "nth-graph" editor.</p>
<p><strong>Grackle</strong> is a "flow-process diagramming" language that runs in many environments, including this browser. 
The diagram below is the source code for the interactive example UI interactivity. For more information about this programming environment, see the project <a href="http://code.google.com/p/nth-graph/">Grackle (formerly: nth-graph)</a>. 
</p>

<div id="example1">
UI interaction: concat(<input type="text" name="a1" id="a1" value="4" />,  <input type="text" name="b1" id="b1" value="2" />) => <span id="sum" >?</span>
</div>
	<div>
      <script type="image/svg+xml">
        <svg width="400" height="300"
             style="background-color: #eee; margin-bottom: 5px;"
             id="diagram-1">
          <g id="diagram-group" 
             fill="#eee" 
             style="font-size: 18px; text-anchor: middle; font-family: serif;">
          </g>
        </svg>
      </script>
    <span id="graph-node-properties">
      <input type="hidden" id="graph-node-index" />
      <textarea id="graph-node-properties-text"  style="width: 600px; height:300px;"></textarea>
        <button id="submit-graph-node-properties">write</button>
      <pre id="graph-node-schema">
{"description":"A node in a grackle diagram (graph definition, not view)",
 "type":"object",
 "properties":
  {"name": {"type":"string", "optional":true},
   "type" : {
     "type":"string",
     "enum":["in", "out", "queryGraph", "controlGraph"],
     "optional":true
   },
   "output":{"type":"object", "optional":true, "requires":"type", "properties":
      {"event":{"type":"object", "properties":
        {"change":{"type":"string", "enum":["immediately"]}}},
       "type":{"type":"string", "optional":true, "enum":["text", "val"]}
      }
   }
  }
}
      </pre>
    </span>
    <span id="graph-edge-properties">
      <input type="hidden" id="graph-edge-index" />
      <textarea id="graph-edge-properties-text"  style="width: 600px; height:300px;"></textarea>
        <button id="submit-graph-edge-properties">write</button>
      <pre id="graph-edge-schema">
{"description":"An edge in a grackle diagram (graph definition, not view)",
 "type":"object",
 "properties":
  {"name": {"type":"string", "optional":true},
   "type" : {"type":"string",
   "enum":["get", "set", "trans", "call"]}
  }
}
      </pre>
    </span>
	</div>
<div>	
        <button onclick="list_graphs();" id="editor_open_button">open</button>
		<button onclick="save_graph();" id="editor_save_button">save</button>
</div>
<div style="display: none" id="list_graphs_dialog">
</div>
<div>
<button id="hide-show-diagram-1-json" >hide/show JSON text</button>
<button id="redraw-diagram-1" >reDraw</button>
<div id="diagram-1-json-text" >
      <textarea id="diagram-1-gv-text" style="width: 600px; height:300px;"></textarea>
      <textarea id="diagram-1-gr-text"  style="width: 600px; height:300px;"></textarea>
</div>
</div>
    
</body>
</html>
